﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DAO;

namespace TAM_SPORT
{
    public partial class Purchase : Form
    {
        private int id = -1;
        private string active ="";
        private bool edit = false;
        public Purchase()
        {
            InitializeComponent();
            edit = false;
        }
        public Purchase(bool edit)
        {
            InitializeComponent();
            this.edit = edit;
        }
        public Purchase(int id)
        {
            edit = true;
            this.id = id;
            InitializeComponent();           
            onload(id);
        }

        private void onload(int id)
        {
            PurchaseDao dao = new PurchaseDao();
            DataRow row = dao.getCustomer(id);
            if (row != null)
            {
                txtName.Text = row["NAME"].ToString();
                active = row["ACTIVE"].ToString();
                rtbNote.Text = row["NOTE"].ToString();
                loadImageCapture(row["PICTURE"].ToString());
                if ("I".Equals(active) || (row["DAY_ONLY"] != null  && "T".Equals(row["DAY_ONLY"].ToString())))
                {
                    DateTime? max = dao.getMaxDateRemind(id);
                    DateTime Expire;
                    if(DateTime.TryParse(row["EXPIRATION_DATE"].ToString(), out Expire))
                    {
                        if(max != null && max > Expire)
                        {
                            TimeSpan diffResult = ((DateTime)max).Subtract(Expire);
                            Confirm fr = new Confirm("Học viên này còn nợ  : " + diffResult.TotalDays.ToString("#,###.##") + " ngày tập. Bạn có muốn lùi ngày đóng tiền hay không? ");
                            fr.ShowDialog();
                            if (fr.IsAccept)
                            {
                                dtpPurchaseDate.Value = DateTime.Now - diffResult;
                            }
                            else
                            {
                                dtpPurchaseDate.Value = DateTime.Now;
                            }
                        }
                        
                    }
                }
                else
                {
                    if (row["EXPIRATION_DATE"].GetType().FullName != "System.DBNull")
                    {
                        dtpPurchaseDate.Value = DateTime.Parse(row["EXPIRATION_DATE"].ToString());
                    }
                    else
                    {
                        dtpPurchaseDate.Value = DateTime.Now;
                    }

                }
            }

        }

        private void btnCapture_Click(object sender, EventArgs e)
        {
            Capture capture = new Capture();
            capture.ShowDialog();
            loadImageCapture(capture.Filename);
        }

        public void setPicture(Image picture)
        {
            this.ptbImage.Image = picture;
        }

        public void loadImageCapture(string filename)
        {
            string path = filename;
            if (!String.IsNullOrEmpty(path))
            {
                try
                {
                    ptbImage.LoadAsync(path);
                    ptbImage.SizeMode = PictureBoxSizeMode.Zoom;
                    ptbImage.Text = filename;
                }
                catch (Exception ex)
                {
                    ptbImage.Image = null;
                    Console.WriteLine(ex);
                }
            }
            else
            {
                if (id <= 0)
                {
                    ptbImage.Image = null;
                }
            }
        }

        private void Purchase_Load(object sender, EventArgs e)
        {
            MasterDao masterDao = new MasterDao();
            DataTable priceTable = masterDao.getPrice();
            cbxPrice.DataSource = priceTable;
            cbxPrice.ValueMember = "ID";
            cbxPrice.DisplayMember = "PRICE";
            DataTable monthTable = masterDao.getMonth();
            cbxMonth.DataSource = monthTable;
            cbxMonth.ValueMember = "ID";
            cbxMonth.DisplayMember = "CMONTH";
            if (txtAmoun.Text.Trim() != "")
            {
                try
                {
                    if (txtAmoun.Text.Trim() != "")
                    {
                        if (cbxMonth.SelectedIndex >= 0)
                        {
                            txtTotal.Text = (float.Parse(txtAmoun.Text) * (cbxMonth.SelectedIndex + 1)).ToString("#,###");
                        }
                    }
                }
                catch
                {
                }
            }
        }

        private void txtAmoun_Validated(object sender, EventArgs e)
        {
            if (txtAmoun.Text.Trim() != "")
            {
                if (cbxMonth.SelectedIndex >= 0)
                {
                    txtTotal.Text = (float.Parse(txtAmoun.Text) * (cbxMonth.SelectedIndex + 1)).ToString("#,###");
                }
            }
            
        }

        private void cbxMonth_SelectedValueChanged(object sender, EventArgs e)
        {
            if (txtTotal.Text.Trim() != "")
            {
                txtTotal.Text = (float.Parse(txtAmoun.Text) * (cbxMonth.SelectedIndex + 1)).ToString("#,###");
            }
            txtExpirationDate.Text = dtpPurchaseDate.Value.AddMonths(cbxMonth.SelectedIndex + 1).ToShortDateString();
        }

       
        private string getImageFolder()
        {
            return SqlHelper.readConfigFile(SqlHelper.IMAGE_FOLDER);
        }

        private void saveImage(string filename)
        {
            Image imge = ptbImage.Image;
            if (imge != null)
            {
                imge.Save(filename);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            string name = txtName.Text.Trim();
            string notes = rtbNote.Text.Trim();
            int month = cbxMonth.SelectedIndex + 1;
            float total = 0;
            if(txtTotal.Text.Trim() != "")
            {
                 total = float.Parse(txtTotal.Text.Trim());
            }
            string path = getImageFolder();
            if (path == null)
            {
                path = "";
            }
            PurchaseDao dao = new PurchaseDao();
            if (name == "" || txtTotal.Text.Trim() == "")
            {
                MessageBox.Show("Vui lòng nhập đầy đủ thông tin");
            }
            else
            {
                DateTime purchaseDate = dtpPurchaseDate.Value;
                String ide = dao.insertPurchase(id, name, notes, month, total, path, purchaseDate);
                if (ide != null && !"0".Equals(ide))
                {
                    bool create = ShareMethod.createFolder(path);
                    if (create)
                    {
                        saveImage(path + ide + ".JPG");
                    }
                    else
                    {
                        Error ers = new Error("Không tạo được thư mục lưu ảnh.");
                        ers.ShowDialog();
                        ers.Dispose();
                    }
                    Result r = new Result(UserConstant.SAVE_SUCCESSFUL);
                    r.ShowDialog();
                    r.Dispose();
                    txtName.Text = "";
                    rtbNote.Text = "";
                    cbxMonth.SelectedIndex = 0;
                    txtAmoun.Text = cbxPrice.Text.Replace(",","");
                    txtTotal.Text = cbxPrice.Text;
                    ptbImage.Image = null;
                    if (edit)
                    {
                        this.Dispose();
                    }
                }
                else
                {
                    MessageBox.Show("Lưu thất bại");
                }
            }
        }

        private void txtAmoun_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            txtName.Text = "";
            rtbNote.Text = "";
            cbxMonth.SelectedIndex = 0;
            txtAmoun.Text = "";
            txtTotal.Text = "";
            ptbImage.Image = null;
        }

        private void dtpPurchaseDate_ValueChanged(object sender, EventArgs e)
        {
            txtExpirationDate.Text = dtpPurchaseDate.Value.AddMonths(cbxMonth.SelectedIndex + 1).ToShortDateString();
        }

        private void txtAmoun_TextChanged(object sender, EventArgs e)
        {
            if (txtAmoun.Text.Trim() != "")
            {
                try
                {
                    if (txtAmoun.Text.Trim() != "")
                    {
                        if (cbxMonth.SelectedIndex >= 0)
                        {
                            txtTotal.Text = (float.Parse(txtAmoun.Text) * (cbxMonth.SelectedIndex + 1)).ToString("#,###");
                        }
                    }
                }
                catch
                {
                }
            }
            else
            {
                txtTotal.Text = "";
            }
        }

        private void txtAmoun_Validating(object sender, CancelEventArgs e)
        {
            if (txtAmoun.Text.Trim() != "")
            {
                txtAmoun.Text = float.Parse(txtAmoun.Text.Replace(",", "")).ToString("#,###");
            }
        }

        private void ptbImage_DoubleClick(object sender, EventArgs e)
        {
            Capture capture = new Capture();
            capture.ShowDialog();
            loadImageCapture(capture.Filename);
        }

        private void cbxPrice_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtAmoun.Text = cbxPrice.Text;
        }

        private void cbxPrice_TextChanged(object sender, EventArgs e)
        {
            txtAmoun.Text = cbxPrice.Text;
            if (RemoveComma(cbxPrice.Text).Length > 3)
            {
                try
                {
                    cbxPrice.Text = decimal.Parse(RemoveComma(cbxPrice.Text)).ToString("#,###");
                    cbxPrice.Select(cbxPrice.Text.Length, 0);
                }
                catch
                {

                }
            }
        }

        private String RemoveComma(String value)
        {
            if (value != null && value.Contains(","))
            {
                value = value.Replace(",", String.Empty).Trim();
            }
            return value;
        }

        private void txtTotal_TextChanged(object sender, EventArgs e)
        {
            if (RemoveComma(txtTotal.Text).Length > 3)
            {
                txtTotal.Text = decimal.Parse(RemoveComma(txtTotal.Text)).ToString("#,###");
                txtTotal.Select(txtTotal.Text.Length, 0);
            }
        }

        private void cbxPrice_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar)
            && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
    }
}
